package com.skivingcloud.admin.sys.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import net.sf.json.JSONObject;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import com.skivingcloud.admin.annotation.UserOperateLog;
import com.skivingcloud.admin.sys.entity.MenuBean;
import com.skivingcloud.admin.sys.entity.SysMenu;
import com.skivingcloud.admin.sys.entity.User;
import com.skivingcloud.admin.sys.service.ISysMenuService;
import com.skivingcloud.admin.utils.UserUtil;
import com.skivingcloud.common.contants.Constant;
import com.skivingcloud.common.exception.BusinessException;
import com.skivingcloud.common.utils.R;
import com.skivingcloud.common.utils.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>
 * 菜单管理 前端控制器
 * </p>
 *
 * @author skivingcloud
 * @since 2022-01-29
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {

	private static Logger log = LoggerFactory.getLogger(SysMenuController.class);

	@Autowired
	private ISysMenuService sysMenuService;
	
	/**
	 * 记录用户菜单点击行为
	 * 
	 * @param menuId
	 * @return
	 */
	@GetMapping("/menuClick/{menuId}")
	// @UserOperateLog(module="系统功能",methods="menuClick",description="菜单点击")
	public R menuClick(@PathVariable("menuId") String menuId) {
		User user = UserUtil.getUser();
		try {
			sysMenuService.menuClick(menuId, user);
		} catch (Exception e) {
			log.error("记录用户菜单点击失败", e);
		}
		return R.ok();
	}

	/**
	 * 列表查询
	 * 
	 * @param params
	 * @return
	 */
	@PostMapping("/list")
	// @RequiresPermissions("sys:menu:list")
	public List<SysMenu> list(@RequestBody Map<String, Object> params) {
		JSONObject obj = StringUtils.isBlank(params.get("dataForm")) ? null
				: JSONObject.fromObject(params.get("dataForm"));
		List<SysMenu> menuList = sysMenuService.selectList(obj);
		return menuList;// menuList;
	}

	/**
	 * 选择菜单(添加、修改菜单)
	 */
	@GetMapping("/select")
	// @RequiresPermissions("sys:menu:select")
	public R select() {
		// 查询列表数据
		List<MenuBean> menuList = sysMenuService.queryNotButtonList();

		// 添加顶级菜单
		MenuBean root = new MenuBean();
		root.setId("0");
		root.setName("菜单");
		root.setParentId("-1");
		root.setOpen(true);
		menuList.add(root);

		return R.ok().put("menuList", menuList);
	}

	@GetMapping("/selectNoRoot")
	// @RequiresPermissions("sys:menu:select")
	public R selectNoRoot() {
		// 查询列表数据
		List<MenuBean> menuList = sysMenuService.queryNotButtonList();

		return R.ok().put("menuList", menuList);
	}

	/**
	 * 菜单信息
	 */
	@GetMapping("/info/{menuId}")
	// @RequiresPermissions("sys:menu:info")
	public R info(@PathVariable("menuId") String menuId) {
		SysMenu menu = sysMenuService.getById(menuId);
		return R.ok().put("menu", menu);
	}

	/**
	 * 新增菜单
	 * 
	 * @param menu
	 * @return
	 */
	@UserOperateLog(module = "系统功能", methods = "save", description = "新增资源")
	@PostMapping("/save")
	// @RequiresPermissions("sys:menu:save")
	public R save(@RequestBody SysMenu menu) {
		try {
			// 数据校验
			verifyForm(menu);
			User user = UserUtil.getUser();
			LocalDateTime date = LocalDateTime.now();
			menu.setCreater(user.getId());
			menu.setCreateTime(date);
			menu.setModUser(user.getId());
			menu.setModTime(date);
			String tenantId = "";
			if (user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
				tenantId = menu.getTenantId();
			} else {
				tenantId = user.getTenantId();
			}
			menu.setTenantId(tenantId);
			sysMenuService.insert(menu);

			return R.ok();
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			return R.error(e.getMessage());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return R.error("系统错误");
		}
	}

	/**
	 * 修改
	 */
	@UserOperateLog(module = "系统功能", methods = "update", description = "更新资源")
	@PostMapping("/update")
	// @RequiresPermissions("sys:menu:update")
	public R update(@RequestBody SysMenu menu) {
		try {
			// 数据校验
			verifyForm(menu);

			sysMenuService.updateByIdMe(menu);

			return R.ok();
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			return R.error(e.getMessage());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return R.error("系统错误");
		}
	}

	/**
	 * 删除
	 */
	@UserOperateLog(module = "系统功能", methods = "delete", description = "删除资源")
	@PostMapping("/delete/{id}")
	// @RequiresPermissions("sys:menu:delete")
	public R delete(@PathVariable("id") String id) {
		if ("1".equals(id) || "2".equals(id) || "3".equals(id) || "4".equals(id)) {
			return R.error("系统基础资源，不能删除");
		}

		// 判断是否有子菜单或按钮
		List<MenuBean> menuList = sysMenuService.queryListParentId(id);
		if (menuList.size() > 0) {
			return R.error("请先删除子菜单或按钮");
		}

		sysMenuService.delete(id);

		return R.ok();
	}

	/**
	 * 验证参数是否正确
	 */
	private void verifyForm(SysMenu menu) {
		if (StringUtils.isBlank(menu.getName())) {
			throw new BusinessException("菜单名称不能为空");
		}

		if (menu.getParentId() == null) {
			throw new BusinessException("上级菜单不能为空");
		}

		// 菜单
		if (menu.getType() == Constant.MenuType.MENU.getValue()) {
			if (StringUtils.isBlank(menu.getUrl())) {
				throw new BusinessException("菜单URL不能为空");
			}
		}

		// 上级菜单类型
		int parentType = Constant.MenuType.CATALOG.getValue();
		if (menu.getParentId() != "0") {
			// Menu parentMenu = sysMenuService.selectById(menu.getParentId());
			// parentType = parentMenu.getType();
		}

		// 目录、菜单
		if (menu.getType() == Constant.MenuType.CATALOG.getValue() ||
				menu.getType() == Constant.MenuType.MENU.getValue()) {
			if (parentType != Constant.MenuType.CATALOG.getValue()) {
				// throw new BusinessException("上级菜单只能为目录类型");
			}
			return;
		}

		// 按钮
		if (menu.getType() == Constant.MenuType.BUTTON.getValue()) {
			if (parentType != Constant.MenuType.MENU.getValue()) {
				// throw new BusinessException("上级菜单只能为菜单类型");
			}
			return;
		}
	}
}
